package com.activity.login;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activity.content.SecGoodsDetail;
import com.activity.fragment.BottomMenuActivity;
import com.activity.fragment.HomeFragment;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tools.Address;
import com.example.login.R;
import com.tools.CommonThings;
import com.tools.OkHttp3;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;


public class LoginActivity extends AppCompatActivity {
    private TextView Register, callWe;
    private Button Login;
    private EditText account, password;
    private ImageView pwdVis, back;
    private Dialog CallWeDialog;
    private Boolean visible = false; //密码可见

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x001) {
                Intent intent = new Intent(LoginActivity.this, BottomMenuActivity.class);
                intent.putExtra("state", "1");
                finish();
                startActivity(intent);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();

        back.setOnClickListener(v->{
            finish();
        });

        Login.setOnClickListener(v -> {
            String acc = String.valueOf(account.getText());
            String pwd = String.valueOf(password.getText());

            if (acc.equals("") || pwd.equals("")){
                Toast.makeText(LoginActivity.this,"请正确填写所有信息",Toast.LENGTH_SHORT).show();
            }else{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", acc);
                jsonObject.put("pwd", pwd);

                RequestBody body = RequestBody.create(MediaType.parse("text/plain"),jsonObject.toJSONString());
                OkHttp3.sendOkHttpPostRequest(Address.getUserLogin(), body, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "服务器连接失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String resPost = response.body().string();
                        Log.d("loginRes", resPost);
                        JSONObject responseJSON = JSONObject.parseObject(resPost);
                        if (responseJSON.getString("code").charAt(0) == '2') {
                            JSONObject dataJSON = responseJSON.getJSONObject("data");
                            JSONObject tokenInfoJSON = dataJSON.getJSONObject("tokenInfo");
                            CommonThings.tokenValue = tokenInfoJSON.getString("tokenValue");
                            CommonThings.userId = tokenInfoJSON.getString("loginId");
                            handler.sendEmptyMessage(0x001);
                        }else if (responseJSON.getString("code").charAt(0) == '5'){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this,responseJSON.getString("message"),Toast.LENGTH_SHORT).show();
                                }
                            });
                        }else{
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "连接出错了",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        });

        Register.setOnClickListener(view -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });

        callWe.setOnClickListener(view -> {
            showDialog();
        });

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!password.getText().toString().equals("")){
                    pwdVis.setVisibility(View.VISIBLE);
                }else{
                    pwdVis.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        pwdVis.setOnClickListener(view -> {
            if (!visible){
                visible = true;
                pwdVis.setImageResource(R.drawable.pwd_vis);
                password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }else {
                visible = false;
                pwdVis.setImageResource(R.drawable.pwd_invis);
                password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            password.setSelection(password.getText().toString().length());
        });
    }

    private void init(){
        back = findViewById(R.id.login_back);
        Login = findViewById(R.id.login_login_btn);
        Register = findViewById(R.id.login_register);
        callWe = findViewById(R.id.login_callWe);

        account = findViewById(R.id.login_account);
        account.setText("admin");
        //设置密码默认不可见
        password = findViewById(R.id.login_password);
        password.setText("111111");
        password.setTransformationMethod(PasswordTransformationMethod.getInstance());

        pwdVis = findViewById(R.id.login_pwd_visible);
    }

    private void showDialog() {
        if (CallWeDialog == null) {
            initShareDialog();
        }
        CallWeDialog.show();
    }

    private void initShareDialog() {
        CallWeDialog = new Dialog(this);
        CallWeDialog.setCanceledOnTouchOutside(true); //手指触碰到外界取消
        CallWeDialog.setCancelable(true);             //可取消 为true
        Window window = CallWeDialog.getWindow();      // 得到dialog的窗体
        window.setGravity(Gravity.BOTTOM);

        View view = View.inflate(this, R.layout.callwe_dialog, null); //获取布局视图
        LinearLayout CallByQQ = view.findViewById(R.id.callwe_qq);

        CallByQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isQQClientAvailable(LoginActivity.this)){
                    final String qqUrl = "mqqwpa://im/chat?chat_type=wpa&uin=2929245593&version=1";
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl)));
                }else{
                    Toast.makeText(LoginActivity.this,"请先安装QQ客户端",Toast.LENGTH_SHORT).show();
                }
            }
        });

        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }

    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            if (pn.equals("com.tencent.mobileqq")) {
                return true;
            }
        }
        return false;
    }
}